//
//  NetImageView.swift
//  Chatup
//
//  Created by iron man on 2024/1/25.
//

import SwiftUI
import Combine

struct NetImageView: View {
    @StateObject private var imageLoader = ImageLoader()
    let url: String
    @State private var dots = "."
    @State var timer: Timer?
        var body: some View {
            Group {
                if let uiImage = imageLoader.image {
                    Image(uiImage: uiImage)
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(maxHeight: 179)
                } else {
                    VStack{
                        Image("ic_mofabang")
                            .resizable()
                            .frame(width: 50, height: 50)
                        Spacer().frame(height: 8)
                        Text("Drawing..." + dots)
                            .font(.system(size: 14).weight(.bold))
                            .foregroundColor(.white)
                            .onAppear {
                                self.timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { _ in
                                    self.dots += "."
                                    if self.dots.count > 3 {
                                        self.dots = "."
                                    }
                                }
                            }
                    }.frame(width: 179, height: 179)
                }
            }
            .onAppear {
                imageLoader.load(fromURLString: url)
            }
        }
}


class ImageLoader: ObservableObject {
    @Published var image: UIImage?

    func load(fromURLString urlString: String) {
        guard let url = URL(string: urlString) else { return }
        
        URLSession.shared.dataTask(with: url) { data, response, error in
            if let data = data, let image = UIImage(data: data) {
                DispatchQueue.main.async {
                    self.image = image
                }
            }
        }.resume()
    }
}

#Preview {
    NetImageView(url: "")
}
